package makefileGenerator;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import file.FileInfo;

public class MakefileBuilder {
	private List<FileInfo> infos = new ArrayList<FileInfo>();
	private MakeFileSource source;

	public MakefileBuilder() {
		source = MakeFileSource.getMakeFileSource();
		for (File file : source.getTexs()) {
			infos.add(new FileInfo(file));
		}
	}

	public MakefileBuilder(MakeFileSource source) {
		this.source = source;
		for (File file : source.getTexs()) {
			infos.add(new FileInfo(file));
		}
	}

	public StringBuilder build() {
		StringBuilder builder = new StringBuilder();
		buildHead(builder);
		buildPDF(builder);
		buildHTML(builder);
		buildIndex(builder);
		buildClean(builder);
		return builder;
	}

	private void buildIndex(StringBuilder builder) {
		builder.append("$(indexobjs) : $(htmlobjs)\n\t	$(INDEXCMD)\n\n");
	}

	private void buildClean(StringBuilder builder) {
		String cmd = ".PHONY : clean\nclean :\n\t-$(DELETECMD) -r $(pdfobjs) $(htmlobjs) $(indexobjs)";
		builder.append(cmd);
	}

	private void buildHead(StringBuilder builder) {
		StringBuilder pdfs = new StringBuilder();
		StringBuilder htmls = new StringBuilder();
		for (FileInfo info : infos) {
			pdfs.append(" " + info.getPdf());
			htmls.append(" " + info.getHtml());
		}
		builder.append("pdfobjs =");
		builder.append(pdfs + "\n");
		builder.append("htmlobjs =");
		builder.append(htmls + "\n");
		builder.append("indexobjs = index.html index_files\n");

		builder.append("PROJECTNAME = texDoc\n");
		builder.append("PDFCMD = " + source.pdfCMD + "\n");
		builder.append("HTMLCMD = " + source.htmlCMD + "\n");
		builder.append("INDEXCMD = " + source.indexCMD + "\n");
		builder.append("DELETECMD =" + source.deleteCMD + "\n\n");
		builder.append("$(PROJECTNAME) : $(pdfobjs) $(htmlobjs) $(indexobjs)\n\n");
	}

	private void buildHTML(StringBuilder builder) {
		String cmd = "$(htmlobjs) :%.html: %.tex\n\t$(HTMLCMD) $<\n\n";
		builder.append(cmd);
	}

	private void buildPDF(StringBuilder builder) {
		String cmd = "\t$(PDFCMD) -output-directory $+\n\t$(PDFCMD) -output-directory $+\n\t$(DELETECMD) $</*.aux $</*.log $</*.out\n\n";
		for (FileInfo info : infos) {
			builder.append(info.getPdf() + " : " + info.getPath() + " "
					+ info.getTex() + "\n");
			builder.append(cmd);
		}
	}
}
